<?php

namespace control;

/*
*收入单类
*/

class otherInReceiptClass extends adIndexClass
{
    private const page = 'otherInReceipt';
    private const table = 'other_receipt';
    private const tableMx = 'other_receipt_detail';
    private const title = '收入单';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'orderNo'          => [
                        'name'  => L('finance.table.dan_ju_bian_hao'),
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'target'  => [
                        'name'  => L('finance.table.wldwlx'),
                        'width' => 200,
                    ],
                    'targetName'         => [
                        'name'  => L('finance.table.wldw'),
                        'width' => 300,
                    ],
                    'money'          => [
                        'name'  => L('finance.table.jin_e') . "(" . static::$unit . ")",
                        'width' => 200,
                    ],
                    'manager'          => [
                        'name'  => L('finance.table.shou_kuan_ren'),
                        'width' => 200,
                    ],
                    'recordDate'          => [
                        'name'  => L('finance.table.dan_ju_ri_qi'),
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'state'          => [
                        'name'  => L('finance.table.zhuang_tai'),
                        'width' => 200,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    L('finance.table.dan_ju_bian_hao') => text(array("name" => "orderNo")),
                    L('finance.table.wldw')   => text(array("name" => "targetName")),
                    L('finance.table.dan_ju_ri_qi') => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ],
                [
                    L('finance.table.zhuang_tai') => select(["name" => "state", 'option' => ['草稿', '待确认', '已确认']]),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url = root . "control/adIndex.html?cla=" . self::page;
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"newIframe('" . L('finance.table.in_info') . "','" . $url . "&fun=edit')\" class='spanButton'>" . L('finance.table.add') . "</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">" . L('finance.table.shan_chu') . "</span>\n";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "orderNo" => $this->post('orderNo'),
        );
        //全等查询数组
        $equal = array(
            "state" => $this->post('state'),
            "targetName" => $this->post('targetName'),
            'coid' => self::$coid,
            'classify' => 2
        );
        $and = '';
        if ($this->post('createTime')) {
            $and .= self::timeComparison($this->post('createTime'), 'date', 'recordDate');
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'recordDate',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "edit" => array("title" => L('finance.table.bian_ji'), "click" => "newIframe('" . L('finance.table.in_info') . "','" . $url . "&fun=edit&id=" . $array['id'] . "')"),
                "detail" => array("title" => L('finance.table.in_info'), "click" => "newIframe('" . L('finance.table.in_info') . "','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
            );
            if ($array['state'] == '已确认') {
                unset($dominate['edit']);
            }
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'money':
                        //收款金额
                        $money = find(array('table' => self::tableMx, 'where' => "orderId = '$array[id]'", 'sum' => "money"));
                        $row[] = $money;
                        break;
                    case 'manager':
                        $row[] = self::findStaff($array['manager']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $totalQuery = find([
            'table'  => self::tableMx,
            'single' => " orderId in (select id from ".self::table." where 1=1 {$where}) ",
            'field'  => "ifnull(sum(money),0) as money",
        ]);
        $total    = [
            'money'        => self::lostZero($totalQuery['money']),
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = $page['hint'] . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 获取收支类别类型
     */
    public function inOutType($type)
    {
        $option = para('cashClassify', '，');
        $data = [];
        foreach ($option as $val) {
            if (str_contains($val, $type . '-')) {
                $data[] = $val;
            }
        }
        return $data;
    }
    /**
     * 保存并提交
     * @return bool|string
     */
    public function saveAndCommit(): bool|string
    {
        $resultJson = $this->editEdit();
        $result = json_decode($resultJson,true);
        if ($result['warn'] == 2){
            unset($_SESSION['warn']);
            $resultJson = $this->commitEdit();
        }
        return $resultJson;
    }
    /**
     * 编辑页
     * @return string
     */
    public function edit(): string
    {
        $id = $this->get('id') ?: suiji();
        $info = query(self::table, " id = '" . $id . "' ");

        $button[] = [
            "name" => '保存为草稿',
            "type" => "点击事件",
            "title" => '保存为草稿',
            'fun' => "subForm('" . self::page . "EditForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=editEdit')"
        ];
        $button[] = [
            'style' => 'li-btn-blue-bg',
            "name" => "保存并提交",
            "type" => "点击事件",
            "title" => "保存",
            'fun' => "subForm('" . self::page . "EditForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=saveAndCommit')"
        ];
        $tr[] = ['', L('finance.table.szxm'), '收款金额(' . static::$unit . ')', L('finance.table.bei_zhu')];
        $result = find(array(
            'field' => "id as mxId,project,money as income,text as mxText",
            'table' => self::tableMx." where orderId = '$info[id]' order by list"
        ));
        if(count($result['array']) > 0) {
            foreach ($result['array'] as $k=>$array) {
                $array['list'] = $k+1;
                $tr[] = $this->listRow($array);
            }
        }else{
            $tr[] = $this->listRow(['mxId'=>self::getId(), 'list'=>1]);
        }
        $total      = [
            2  => "<span id='total_money'>" . self::lostZero(array_sum(array_column((array)$result['array'],'income'))) . "</span>",
        ];

        //表单
        $data['button'] = $this->tableShowButton($button);
        $body = $this->edit4([
            '基本信息' => [
                [
                    must . L('finance.table.ye_wu_lei_xing') . "：" => radio(array('name' => 'type', 'value' => ['收款结算' => L('finance.table.incomeSettle'), '其他应收' => L('finance.table.otherInCome')], 'checked' => $info['type'] ?: '收款结算')),
                    L('finance.table.wldw') . "：" => text(array('name' => 'targetName', 'id' => 'targetName', 'value' => $info['targetName'])) . hidden(array('name' => 'targetId', 'value' => $info['targetId'])) . hidden(array('name' => 'target', 'value' => $info['target'])),
                    must . L('finance.table.dan_ju_ri_qi') . "：" => text(["name" => "recordDate", 'laydate' => [], "value" => $info['recordDate'] ?: $this->date]),
                    must ."结算账户：" => componentClass::subjectComponent(['name' => 'acid','value'=>$info['acid'], 'inputName' => 'costSubjectName', 'isShowParent' => false])

                ],
                [
                    L('finance.table.shou_kuan_ren') . "：" => selectMultiple(["name" => "manager", "value" => $info['manager'] ?: self::$stid, 'where' => "state !='离职'", 'table' => "staff", 'sqlId' => 'stid', 'sqlField' => 'name', 'title' => L('finance.table.qing_xuan_ze')]),
                ],
                [
                    L('finance.table.text') . "：" => textarea(["name" => "text", "value" => $info['text']]),
                ],
            ]
        ]);
        $body .= $this->editList([
            'title' => L('finance.table.shou_ru_ming_xi'),
            'html' => $this->listTable(array('tr' => $tr, 'end' => true, 'total' => $total)),
        ]);
        $data['html'] = $this->pageEdit([
            "html" => $body,
            'hidden' => hidden(['name' => 'id', 'value' => $id]),
        ]);
        $data['html'] .= <<<efo
<script>
$("#targetName").bigAutocomplete({
    width:200,
    url:root + 'control/adIndex.html?cla={$this->get('cla')}&fun=getCompany',
    callback:function(data,e){
       e.siblings("input[name='targetId']").val(data.id)
       $("[name='target']").val(data.target)
}}) 
function addRow(e){
    $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addRow',{},function (res){
            $(e).closest('tr').after(res.data);
            resetNumber($(e).closest('tbody'))
            calculateTotal()
         },'json');
}
//合计
function calculateTotal(table=''){
    table = table ? table : $('.editList')
    let money = 0
    table.find("[name='income[]']").each(function(index){
        if($(this).val()){
          money+=Number($(this).val());
        }
    })
    $("#total_money").text(money.toFixed(amountPrecision));
}
</script>

efo;
        //返回
        return $this->tab($data);
    }


    /**
     * 往来单位
     * @return bool|string
     */
    public function getCompany(): bool|string
    {
        $val = $this->post('keyword');//关键词
        $json['data'] = [];
        $where = "";
        if ($val) {
            $where .= " and (companyName like '%$val%' or orderNo like '%$val%')";
        }
        $all = find(array('table' => 'kehu', 'where' => "coid = '" . self::$coid . "'  $where order by orderNo asc limit 50"));
        foreach ($all['array'] as $array) {
            $json['data'][] = array('title' => $array['companyName'], 'orderNo' => $array['orderNo'], 'target' => L('finance.table.ke_hu'), 'id' => $array['khid']);
        }
        $where = '';
        if ($val) {
            $where .= " and (name like '%$val%' or code like '%$val%')";
        }
        $all = find(array('table' => 'supplier', 'where' => "coid = '" . self::$coid . "'  $where order by code asc limit 50"));
        foreach ($all['array'] as $array) {
            $json['data'][] = array('title' => $array['name'], 'orderNo' => $array['code'], 'target' => L('finance.table.gong_ying_shang'), 'id' => $array['id']);
        }
        $json['warn'] = 2;
        return json_encode($json, 320);
    }

    /**
     * Desc : 收入明细
     * User : you name
     * Date : 2024-02-20 14:51
     * @param array $data
     * @return array|false|string
     */
    public function listRow($data=[])
    {
        $list = isset($data['list'])?$data['list']:'';
        $mxId = isset($data['mxId'])&&$data['mxId']?$data['mxId']:self::getId();
        $field = ['project', 'income', 'mxText'];
        foreach ($field as $item){
            $array[$item] = isset($data[$item])?$data[$item]:$this->post($item);
        }
        $cloneArg = json_encode([
            'cla' => self::page,
            'fun' => 'listRow',
            'copy' => $field,
            'callback' => "calculateTotal()",
        ],320);
        $delArg = json_encode([
            'empty' => $field,
        ],320);
        $tr = [
            componentClass::tablePperation($list, "delRows(this,$delArg);calculateTotal()","cloneRows(this,$cloneArg)", "addRow(this)"),
            hidden(array('name' => 'mxId[]', 'value' => $mxId)) .
            select(array('name' => 'project[]', 'title' => L('finance.table.szxm'), 'option' => $this->inOutType('收'), 'value' => $array['project'])),
            text(array('name' => 'income[]', 'value' => $array['income'], 'other' => " onblur='calculateTotal()' ")),
            text(array('name' => 'mxText[]', 'class' => 'text textPrice', 'value' => $array['mxText'])),
        ];
        if($data){
            return $tr;
        }
        $json['html'] = $this->tableMany(['tr' => [$tr], 'thead' => false]);
        return json_encode($json, 320);
    }

    /**
     *添加一行
     */
    public function addRow()
    {
        $res = json_decode($this->listRow(),true);
        $json['data'] = $res['html'];
        return json_encode($json, 320);
    }
    public function editEdit()
    {
        $id = $this->post('id') ?: self::getId();
        //收款
        $mxIdArr = $this->post('mxId') ?: [];
        $incomeArr = $this->post('income');
        $projectArr = $this->post('project');
        $mxTextArr = $this->post('mxText');

        $field = [
            'type' => $this->post('type'),
            'target' => $this->post('target'),
            'targetId' => $this->post('targetId'),
            'text' => $this->post('text'),
            'recordDate' => $this->post('recordDate'),
            'manager' => $this->post('manager'),
            'targetName' => $this->post('targetName'),
            'acid' => $this->post('acid'),
        ];
        $where = " id = '$id' ";
        $info = query(self::table, $where);
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = L('finance.table.in_edit_permission');
        } elseif (!empty($info['id']) && $info['state'] == '已确认') {
            $json['warn'] = L('finance.table.cdjyqrbnxg');
        } else {
            $this->startTrans();
            $isPass = true;//事务通过标志
            if (!$info['id']) {
                $userNo = $orderNo = codeTemplateClass::generateCode(self::page, [
                    'prefix' => 'QTSR' . date('Ymd', strtotime($field['recordDate'])),
                    'table' => self::table,
                    'field' => 'orderNo',
                    'where' => " and coid = '" . self::$coid . "'",
                ], $field);
                $field = array_merge($field, [
                    'id' => $id,
                    'orderNo' => $userNo,
                    'state' => '草稿',
                    'classify' => 2,
                    'coid' => self::$coid,
                    'stid' => $this->control['stid'],
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where
                ]);
                $orderNo = $info['orderNo'];
            }
            //明细
            foreach ($mxIdArr as $k => $nid) {
                $mx = query(self::tableMx, "id = '$nid'");
                if (!empty($mx['id'])) {
                    //更新
                    $warn = static::update([
                        "table" => self::tableMx,
                        "field" => [
                            'money' => $incomeArr[$k],
                            'project' => $projectArr[$k],
                            'text' => $mxTextArr[$k],
                        ],
                        "where" => " id = '$nid'"
                    ]);
                } else {
                    //新增
                    $warn = static::insert([
                        "table" => self::tableMx,
                        "field" => [
                            'id' => $nid,
                            'orderId' => $id,
                            'coid' => self::$coid,
                            'money' => $incomeArr[$k],
                            'project' => $projectArr[$k],
                            'text' => $mxTextArr[$k],
                        ],
                    ]);
                }
                if (!in_array($warn, ['新增成功', '更新成功'])) {
                    $isPass = false;
                    $json['warn'] = $warn;
                    break;
                }

                //生成记账表
                if ($field['type'] == '收款结算' && $field['acid']) {
                    $bookkeeping = query('bookkeeping', "sourceId = '$nid'");

                    $account = query('account', "subjectId = '$field[acid]'");
                    if (empty($account['id'])){
                        $json['warn'] = '未找到此账户';
                    }
                    if (empty($bookkeeping['id'])) {
                        $page = $account['type'] == '现金' ? 'cashBook' : 'bankBook';
                        $fieldBookkeeping = [
                            'id' => suiji(),
                            'type' => $account['type'] == '现金' ? '现金' : '银行账户',
                            'coid' => self::$coid,
                            'stid' => self::$stid,
                            'accountId' => $account['id'],
                            'classify' => $projectArr[$k],
                            'recordDate' => $field['recordDate'],
                            'company' => $field['targetName'],
                            'summary' => "收入单【{$orderNo}】",
                            'income' => $incomeArr[$k],
                            'text' => $mxTextArr[$k],
                            'sourceTable' => self::tableMx,
                            'sourceId' => $nid,
                        ];
                        $userNo = codeTemplateClass::generateCode($page, [
                            'prefix' => date('Ymd', strtotime($field['recordDate'])),
                            'table' => 'bookkeeping',
                            'field' => 'orderNo',
                            'where' => " and coid = '" . self::$coid . "'",
                        ], $fieldBookkeeping);
                        $fieldBookkeeping['orderNo'] = $userNo;
                        $warn = static::insert([
                            "table" => "bookkeeping",
                            "field" => $fieldBookkeeping,
                        ]);
                    } else {
                        $warn = static::update([
                            "table" => "bookkeeping",
                            "field" => [
                                'accountId' => $account['id'],
                                'classify' => $projectArr[$k],
                                'recordDate' => $field['recordDate'],
                                'company' => $field['targetName'],
                                'summary' => "收入单【{$orderNo}】",
                                'income' => $incomeArr[$k],
                                'text' => $mxTextArr[$k],
                            ],
                            'where' => "id = '$bookkeeping[id]'"
                        ]);
                    }
                    if (!in_array($warn, ['新增成功', '更新成功'])) {
                        $isPass = false;
                        $json['warn'] = L('finance.table.scjzbsb');
                        break;
                    }
                }

            }

            if (in_array($json['warn'], ["新增成功", "更新成功"]) && $isPass) {
                $this->commitTrans();
                delete(array('table' => 'bookkeeping', 'where' => " sourceId in (select id from " . self::tableMx . " where id not in ('" . implode("','", $mxIdArr) . "') and orderId = '$id') and coid = '" . self::$coid . "'"));
                delete(array('table' => self::tableMx, 'where' => " id not in ('" . implode("','", $mxIdArr) . "') and orderId = '$id'"));
                if ($json['warn'] == '新增成功') {
                    self::insertOperateLog($id,self::title,"新建");
                }
                //添加日志
                $text = str_replace(['{{staffName}}', '{{orderNo}}', '{{id}}'], [$this->control['name'], $orderNo, $id], L('finance.table.in_edit_text'));
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
            } else {
                $this->rollback();
            }
        }
        resp:
        return json_encode($json, 320);
    }


    /*详情页*/
    public function detail(): string
    {
        $info = query(self::table, " id = '{$this->get('id')}'");
        if (empty($info['id'])) {
            $html = L('finance.table.wzdcsrd');
        } else {
            //菜单
            $data = array(
                "id" => $info['id'],
            );

            $button = [];
            if ($this->power(self::page, "confirm") && $info['state'] == '待确认') {
                $button[] = [
                    "name" => '复核',
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'confirm', "id" => $info['id']],
                    'style' => 'li-btn-blue-bg',
                ];
            }

            if ($info['state'] == '草稿') {
                if ($this->power(self::page, "edit")) {
                    //按钮
                    $button[] = [
                        "name" => L('finance.table.ti_jiao'),
                        "type" => "弹出层",
                        "cla" => $this->get('cla'),
                        "fun" => "operate",
                        "post" => ["act" => 'commit', "id" => $info['id']],
                        'style' => 'li-btn-blue-bg',
                    ];
                    //按钮
                    $button[] = [
                        "name" => L('finance.table.bian_ji'),
                        "type" => "顶部页卡",
                        "title" => L('finance.table.bian_ji'),
                        "url" => $this->root . "control/adIndex.html?cla={$this->get('cla')}&fun=edit&id=" . $info['id'],

                    ];
                }
                if ($this->power(self::page, "del")) {
                    //按钮
                    $button[] = [
                        "name" => L('finance.table.shan_chu'),
                        "type" => "弹出层",
                        "cla" => $this->get('cla'),
                        "fun" => "operate",
                        "post" => ["act" => 'del', "id" => $info['id']],
                    ];
                }
            }

            if ($this->power(self::page, "cancel") && $info['state'] != '草稿') {
                $button[] = [
                    "name" => "撤销",
                    "type" => "弹出层",
                    "cla"  => $this->get('cla'),
                    "fun"  => "operate",
                    "post" => ["act" => 'cancel', "id" => $info['id']],
                ];
            }
            //操作记录
            $button[] = self::operateLogBut($info['id'],1);

            $tr[] = [L('finance.table.szxm'), L('finance.table.receiveMoney') . '(' . static::$unit . ')', L('finance.table.bei_zhu')];
            $result = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list"));
            foreach ($result['array'] as $array) {

                $tr[] = [
                    $array['project'],
                    $array['money'],
                    $array['text'],
                ];
            }
            $income = find(array('table' => self::tableMx, 'sum' => "money", 'where' => "orderId = '$info[id]'"));
            $total_tr = [
                    1=>$income
            ];
            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html'] = $this->tableShow(array(
                '基本信息' => array(
                    array(
                        L('finance.table.ye_wu_lei_xing') => $info['type'],
                        L('finance.table.wldw') => $info['targetName'],
                        L('finance.table.dan_ju_ri_qi') => $info['recordDate'],
                        "结算账户" =>subjectClass::getShortName($info['acid'],'code'). subjectClass::getName($info['acid']),
                    ),
                    array(
                        L('finance.table.shou_kuan_ren') => self::findStaff($info['manager']),
                        L('finance.table.dan_ju_bian_hao') => $info['orderNo'],
                        L('finance.table.zhi_dan_ren') => self::findStaff($info['stid']),
                        L('finance.table.zhuang_tai') => $info['state']
                    ),
                    array(
                        L('finance.table.bei_zhu') => pre($info['text']),
                    ),
                ),
            ));
            $data['html'] .= $this->detailList([
                'title' => L('finance.table.shou_ru_ming_xi'),
                'html' => $this->listTable(array('tr' => $tr, 'showEmpty' => true, 'total' => $total_tr, 'showSort' => true)),
            ]);
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }

    /**
     * 确认
     */
    public function confirmEdit()
    {
        $id = $this->post('id');
        $info = query(self::table, " id = '$id'");
        $field = [
            'state' => '已确认',
            'checkId' => self::$stid,
            'confirmTime' => $this->time
        ];
        if (!$this->power(self::page, 'confirm')) {
            $json['warn'] = L('finance.table.nhmzqrzx');
        } elseif (empty($info['id'])) {
            $json['warn'] = L('finance.table.wzdcsrd');
        } elseif ($info['state'] != '待确认') {
            $json['warn'] = L('finance.table.csrdbsdqrztbnqr');
        } else {
            $this->startTrans();
            $json['warn'] = update(array(
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ));
            if ($info['type'] == '收款结算') {
                $all = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list"));
                foreach ($all['array'] as $array) {
                    $account = query('account',"subjectId = '$info[acid]'");
                    $bool = accountClass::record_ac($account['id'], '收入', $array['money'], "收入单【{$info['orderNo']}】收入", targetName: $info['targetName'], targetDate: $info['recordDate'], orderNo: $info['orderNo'], hiddenText: "收入单【{$info['orderNo']}】收入，明细ID：{$array['id']}");
                    if ($bool !== true) {
                        $json['warn'] = $bool;
                        break;
                    }
                }
            }

            if ($info['type'] == '其他应收') {
                $remindMoney = find(['table' => self::tableMx, 'where' => "orderId = '$info[id]'", 'sum' => "money"]);
                if ($info['target'] =='客户'){
                    $bool = supplierClass::record_cl($info['targetId'], '+', $remindMoney, $info['recordDate'], self::table, $info['id'], "收入单【{$info['orderNo']}】收款", orderNo: $info['orderNo'], hiddenText: "收入单类型为其他应收", classify:$info['type']);
                }else{
                    $bool = supplierClass::record_cl($info['targetId'], '-', -$remindMoney, $info['recordDate'], self::table, $info['id'], "收入单【{$info['orderNo']}】收款",'供应商', orderNo: $info['orderNo'], hiddenText: "收入单类型为其他应收", classify: $info['type']);
                }

                if ($bool !== true) {
                    $json['warn'] = $bool;
                }
            }

            if (in_array($json['warn'], ["更新成功"])) {
                // 单据是否需要复核
                if(!in_array(self::page,self::$publicSettings['documentReview'])) {
                    self::insertOperateLog($info['id'],self::title,"提交、复核");
                }else{
                    self::insertOperateLog($info['id'],self::title,"复核");
                }
                $this->commitTrans();
                //添加日志
                $text = str_replace(['{{staffName}}', '{{orderNo}}', '{{id}}'], [$this->control['name'], $info['orderNo'], $id], L('finance.table.in_confirm_text'));
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            } else {
                $this->rollback();
            }
        }
        resp:
        return json_encode($json, 320);
    }

    /**
     * Desc : 提交前数据验证
     * User : you name
     * Date : 2023-11-17 16:04
     * @param $info
     * @return string|bool
     */
    public function dataValidation($info): string|bool
    {
        $annotation = [
            'type' => L('finance.table.ye_wu_lei_xing'),
            'recordDate' => L('finance.table.dan_ju_ri_qi'),
            'acid' => "结算账户",
        ];
        $rules = [
            'type' => 'required',
            'recordDate' => 'required',
            'acid' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($info, $rules)->isOk();
        if ($result === false) {
            return $vt->getErrs()[0];  // 多个规则提示最前面一条
        }
        if ($info['type'] == '其他应收' && empty($info['targetId'])) {
            return '请选择往来单位';
        }
        $result = find(array('table' => self::tableMx, 'field' => 'id,money,project', 'where' => "orderId = '$info[id]' order by list"));
        if(count($result['array']) == 0){
            return "请完善收入明细";
        }
        if(static::is_null_array(array_column($result['array'],'project'))){
            return "收入明细中【收支项目】不能为空";
        }
        if(static::is_null_array(array_column($result['array'],'money'),false)){
            return "收入明细中【收款金额】不能为空，且必须大于0";
        }

        return true;
    }
    /**
     * 提交
     */
    public function commitEdit()
    {
        $id = $this->post('id');
        $info = query(self::table, " id = '$id'");
        $field = [
            'state' => '待确认',
        ];
        //提交前数据验证
        $json['warn'] = $this->dataValidation($info);
        if($json['warn'] !== true){
            goto resp;
        }
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = L('finance.table.nhmzbjzx');
        } elseif (empty($info['id'])) {
            $json['warn'] = L('finance.table.wzdcsrd');
        } elseif ($info['state'] != '草稿') {
            $json['warn'] = L('finance.table.csrdbscgztbntj');
        } else {
            $this->startTrans();
            $json['warn'] = update(array(
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                // 单据是否需要复核
                if(!in_array(self::page,self::$publicSettings['documentReview'])){
                    $resultJson = $this->confirmEdit();
                    $json = json_decode($resultJson,true);
                    if ($json['warn'] != 2){
                        $this->rollback();
                        goto resp;
                    }
                }else {
                    self::insertOperateLog($info['id'],self::title,"提交");
                }
                $this->commitTrans();
                //添加日志
                $text = str_replace(['{{staffName}}', '{{orderNo}}', '{{id}}'], [$this->control['name'], $info['orderNo'], $id], L('finance.table.in_commit_text'));
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            } else {
                $this->rollback();
            }
        }
        resp:
        return json_encode($json, 320);
    }

    /**
     * 撤销
     */
    public function cancelEdit()
    {
        $id    = $this->post('id');
        $info  = query(self::table, " id = '$id'");
        $field = [
            'state'       => '草稿',
            'checkId'     => '',
            'confirmTime' => '',
        ];
        $warn='';
        if ($info['type'] =='其他应收'){
            $record = query('record', "typeId = '$info[targetId]' and coid = '" . self::$coid . "' and sourceId = '$info[id]'");
            if ($record['id'] && static::total(array('table' => 'record', 'where' => "typeId = '$info[targetId]' and coid = '" . self::$coid . "' and id > '$record[id]'")) > 0) {
                $warn     = "{$info['target']}【{$info['targetName']}】已生成了后续应付应收记录，不能撤销";
            }
        }
        if (!$this->power(self::page, 'cancel')) {
            $json['warn'] = '你还没有撤销权限';
        } elseif (empty($info['id'])) {
            $json['warn'] = '未找到此单据';
        } elseif ($info['state'] != '已确认') {
            $json['warn'] = '此单据不是已确认状态，无需撤销';
        } elseif ($warn) {
            $json['warn'] = $warn;
        } elseif ($info['voucherId']) {
            $json['warn'] = '此单据已生成凭证，不能撤销';
        } else {
            $json['warn'] = update(array(
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //删除应收应付记录
                delete(array('table' => 'record', 'where' => "typeId = '$info[targetId]' and coid = '" . self::$coid . "' and sourceId = '$info[id]'"));
                self::insertOperateLog($id,self::title,"撤销");
                //添加日志
                $text = $this->control['name'] . "撤销了" . self::title . "，单据编号【{$info['orderNo']}】id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn']     = 2;
                $json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            }
        }
        resp:
        return json_encode($json, 320);
    }

    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = $word = false; // 需要密码
        switch ($act) {
            case 'confirm':
                $act = 'confirm';
                $msg = L('finance.table.que_ren');
                $title = L('finance.table.sfyqrcsrdqrhjbkxg');
                $function = 'confirmEdit';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                $word = true;
                break;
            case 'commit':
                $act = 'edit';
                $msg = L('finance.table.bian_ji');
                $title = L('finance.table.sfqrtjcsrd');
                $function = 'commitEdit';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                $word = true;
                break;
            case 'cancel':
                $act      = 'cancel';
                $msg      = '撤销';
                $title    = '是否确认撤销此单据？';
                $function = 'cancelEdit';
                $form     = self::page . 'OperateForm, detailForm';
                $power    = '';
                $word     = true;
                break;
            default:
                $act = 'del';
                $msg = L('finance.table.in_del');
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm, quoForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = str_replace(['{{msg}}'], [$msg], L('jon.other.permission_warn'));
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
                'word' => $word
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = L('finance.table.nmzscdzx');
        } elseif (empty($array)) {
            $json['warn'] = L('finance.table.nygsjdmzxzn');
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                if ($info['state'] == '已确认') {
                    $warn = L('finance.table.fee_del_failed');
                } else {
                    //最后删除基本参数
                    delete(array("table" => 'bookkeeping', "where" => " sourceId in (select id from " . self::tableMx . " where orderId = '$id')"));
                    delete(array("table" => self::table, "where" => " id = '$id' "));
                    delete(array("table" => self::tableMx, "where" => " orderId = '$id' "));
                    delete(array("table" => "auditing_follow", "where" => " typeId = '$id' "));
                    //返回
                    $warn = L('finance.table.sccg');
                    $x++;
                }
                $text .= str_replace(['{{orderNo}}', '{{id}}'], [$info['orderNo'], $info['id']], L('finance.table.in_del_text')) . $warn . "。<br>";
            }
            //添加日志
            $text = str_replace(['{{staffName}}'], [$this->control['name']], L('finance.table.in_del_log')) . "<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = str_replace(['{{x}}'], [$x], L('finance.table.in_del_msg'));
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }
}

